package com.momochen.alarmclockdemo;

import android.app.Application;

import com.momochen.alarmclockdemo.db.DaoMaster;
import com.momochen.alarmclockdemo.db.DaoSession;

import org.greenrobot.greendao.database.Database;

/**
 * Created by momochen on 2017/7/9.
 */

public class AppContext extends Application {
    //数据库
    protected DaoSession daoSession;

    //单例
    private static AppContext instance;

    @Override
    public void onCreate() {
        super.onCreate();

        instance = this;

        initDB();
    }

    /**
     * 获得当前app运行的AppContext
     *
     * @return
     */
    public static synchronized AppContext getInstance() {
        return instance;
    }

    /**
     * 初始化数据库
     */
    protected void initDB() {
        //数据库
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db");
        Database db = helper.getWritableDb();
        daoSession = new DaoMaster(db).newSession();
    }

    /**
     * 获取数据库
     *
     * @return
     */
    public synchronized DaoSession getDaoSession() {
        if (daoSession == null) {
            initDB();
        }
        return daoSession;
    }
}
